function setTab(defaultIndex)
{
    var self = plus.webview.currentWebview();
    var tabList = document.querySelectorAll(".mui-tab-item");
    for(var i = 0; i < tabList.length; i++){
        var href = tabList[i].getAttribute("href");
        var sub = plus.webview.create(href, href, {top: "45px", bottom: "51px"});
        if(i != defaultIndex){
            sub.hide();
        }
        else{
            tabList[i].classList.add("mui-active");
            tabList[i].classList.add("has-show");
        }
        self.append(sub);
    }
}

function doTap(e)
{
    var href = this.getAttribute("href");
    var hasActive = this.classList.contains("mui-active");
    var hasShow = this.classList.contains("has-show");
    /*点了当前的*/
    if(hasActive){
        return;
    }
    if(hasShow || mui.os.ios){
        plus.webview.show(href);
    }
    else{
        plus.webview.show(href, "fade-in", 300);
        this.classList.add("mui-active");
        this.classList.add("has-show");
    }
    var before = document.querySelector(".mui-active");
    plus.webview.hide(before.getAttribute("href"));
    before.classList.remove("mui-active");
}

// function addHtml(element, position, templateId, data, callback)
// {
//     var html = template(templateId, data);
//     element.insertAdjacentHTML(position, html);
//     if(callback){
//         callback(data);
//     }
// }

function addHtml(itemBoxId, position, html)
{
    var itemBox = document.body.querySelector(itemBoxId);
    itemBox.insertAdjacentHTML(position, html);
}

function requestUrl(method, url, callback, data)
{
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4 && xhr.status == 200){
            callback(JSON.parse(xhr.responseText));
        }
    };
    xhr.open(method, url);
    if(data){
        xhr.send(data);
    }
    else{
        xhr.send();
    }
}

function loadJsSort(list, index, callback)
{
    var src = list[index];
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = src;
    document.getElementsByTagName("body")[0].appendChild(script);
    script.onload = function(){
        var nextIndex = index + 1;
        if(nextIndex == list.length){
            callback();
        }
        else{
            loadJsSort(list, nextIndex, callback);
        }
    };
}

function xxopenWindow(url)
{
    mui.openWindow({
        url: url,
        show: {
            autoShow: true
        },
        styles: {
            top: "45px",
            bottom: "51px"
        }
    });
}

function xdssssopenWindow(url)
{
    mui.openWindow({
      url: url,
      id: url,
      styles: {                             // 窗口参数 参考5+规范中的WebviewStyle,也就是说WebviewStyle下的参数都可以在此设置
        titleNView: {                       // 窗口的标题栏控件
          titleText:"标题栏",                // 标题栏文字,当不设置此属性时，默认加载当前页面的标题，并自动更新页面的标题
          titleColor:"#000000",             // 字体颜色,颜色值格式为"#RRGGBB",默认值为"#000000"
          titleSize:"17px",                 // 字体大小,默认17px
          backgroundColor:"#F7F7F7",        // 控件背景颜色,颜色值格式为"#RRGGBB",默认值为"#F7F7F7"
          progress:{                        // 标题栏控件的进度条样式
            color:"#00FF00",                // 进度条颜色,默认值为"#00FF00"
            height:"2px"                    // 进度条高度,默认值为"2px"
          },
          splitLine:{                       // 标题栏控件的底部分割线，类似borderBottom
            color:"#CCCCCC",                // 分割线颜色,默认值为"#CCCCCC"
            height:"1px"                    // 分割线高度,默认值为"2px"
        }
        }
      }
    });
}

function openWindow(url, title)
{
    var styles = {
        titleNView: {
            autoBackButton: true,
            titleText: title,
            titleColor: "#007aff",
            titleSize: "17px",
            backgroundColor: "#F7F7F7",
            progress: {color: "#00FF00", height: "2px"},
            splitLine: {color: "#CCCCCC", height: "1px"}
        }
    };
    mui.openWindow({url: url, id: url, styles: styles});
}

function openWindowWithRightButton(url)
{
    mui.openWindow({url: url, id: url});
}

function autoOpenUrl(id, url, title)
{
    document.getElementById(id).addEventListener("tap", function(){
        openWindow(url, title);
    });
}

function setPlayer(id, source)
{
    var player = new Aliplayer({
      "id": id,
      "source": source,
      "width": "100%",
      "height": "200px",
      "autoplay": false,
      "isLive": false,
      "rePlay": false,
      "playsinline": true,
      "preload": true,
      "controlBarVisibility": "always",
      "useH5Prism": true,
      "skinLayout": [
        {
          "name": "controlBar",
          "align": "blabs",
          "x": 0,
          "y": 0,
          "children": [
            {
              "name": "progress",
              "align": "blabs",
              "x": 0,
              "y": 44
            },
            {
              "name": "playButton",
              "align": "tl",
              "x": 15,
              "y": 12
            },
            {
              "name": "timeDisplay",
              "align": "tl",
              "x": 10,
              "y": 7
            },
            {
              "name": "fullScreenButton",
              "align": "tr",
              "x": 10,
              "y": 12
            },
            {
              "name": "volume",
              "align": "tr",
              "x": 5,
              "y": 10
            }
          ]
        }
      ]
    }, function (player) {
        console.log("播放器创建了。");
      }
    );
}

function reBindEvent()
{
    if((typeof reBindEventForPage) == 'function'){
        reBindEventForPage();
    }
}

function pullUpRefreshVideoCallback()
{
    requestUrl('GET', apiVideoListUrl, function(json){
        var data = json.data;
        addHtml('#itemBox', 'beforeend', data.html);
        initPlayer(data.playerIds);
        mui(pullRefreshContainerId).pullRefresh().endPullupToRefresh(data.end);
        reBindEvent();
    }, false);
}

function pullDownRefreshVideoCallback()
{
    requestUrl('GET', apiVideoListUrl, function(json){
        var data = json.data;
        addHtml('#itemBox', 'afterbegin', data.html);
        initPlayer(data.playerIds);
        mui(pullRefreshContainerId).pullRefresh().endPulldownToRefresh(data.end);
        reBindEvent();
    }, false);
}

function pullUpRefreshVideoCommentCallback()
{
    requestUrl('GET', apiVideoCommentListUrl, function(json){
        var data = json.data;
        addHtml('#itemBox', 'beforeend', data.html);
        mui(pullRefreshContainerId).pullRefresh().endPullupToRefresh(data.end);
    }, false);
}

function pullDownRefreshVideoCommentCallback()
{
    requestUrl('GET', apiVideoCommentListUrl, function(json){
        var data = json.data;
        addHtml('#itemBox', 'afterbegin', data.html);
        mui(pullRefreshContainerId).pullRefresh().endPulldownToRefresh(data.end);
    }, false);
}

function initPullRefresh(container, pullUpRefreshCallback, pullDownRefreshCallback)
{
    mui.init({
        pullRefresh: {
            container: container,
            up: {
                auto: true,
                contentrefresh: '正在加载',
                callback: pullUpRefreshCallback
            },
            down: {
                style: 'circle',
                callback: pullDownRefreshCallback
            }
        }
    });
}

function initPlayer(playerIds)
{
    for(i in playerIds){
        var source = document.body.querySelector('#' + playerIds[i]).getAttribute('source');
        setPlayer(playerIds[i], source);
    }
}

function $$(id)
{
    return document.getElementById(id);
}

function isPhone(value){
    return /^1[3-9]{1}\d{9}$/.test(value);
}

function isMessageCode(code)
{
    var codeInt = parseInt(code);
    if(isNaN(codeInt)){
        return false;
    }
    if(codeInt == code && code >= 100000 && code <= 999999){
        return true;
    }
    else{
        return false;
    }
}